package com.fly.filesend.controller;

import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.core.qr.QRCodeUtil;
import com.fly.filesend.entity.JsonResult;
import com.fly.filesend.service.TokenService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@Api(tags = "系统接口")
@RestController
@RequestMapping("/api")
public class ApiController
{
    @Autowired
    HttpSession httpSession;
    
    @Autowired
    TokenService tokenService;
    
    @ApiOperationSupport(order = 10)
    @PostMapping("/login")
    @ApiOperation("登录系统")
    public JsonResult<?> login(String token)
    {
        if (!tokenService.valide(token))
        {
            return JsonResult.error("token empty or valide failed!");
        }
        httpSession.setAttribute("token", token);
        String date = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        return JsonResult.success(date + " login success!");
    }
    
    @ApiOperationSupport(order = 20)
    @PostMapping("/logout")
    @ApiOperation("退出系统")
    public JsonResult<?> logout()
    {
        httpSession.invalidate();
        String date = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        return JsonResult.success(date + " logout success!");
    }
    
    @ApiOperation("生成二维码")
    @ApiImplicitParam(name = "content", value = "二维码文本", required = true, example = "乡愁是一棵没有年轮的树,永不老去")
    @PostMapping(value = "/qr/create", produces = MediaType.IMAGE_JPEG_VALUE)
    public void index(String content, HttpServletResponse response)
        throws Exception
    {
        BufferedImage image;
        if (StringUtils.isNotBlank(content))
        {
            Resource resource = new ClassPathResource("img/dog.jpg");
            URL imgURL = resource.getURL();
            image = QRCodeUtil.createImage(content, imgURL, true);
        }
        else
        {
            image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
        }
        // 输出图象到页面
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
